<template>
  <div class="modal">
    <!-- 遮罩 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 登陆内容 -->
    <div class="loginbox">
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <section class="nav">
        <a
          href="javascript:void(0);"
          :class="{ active: isShowPhone }"
          @click="isShowPhone = true"
          >手机号登录</a
        >
        |
        <a
          href="javascript:void(0);"
          :class="{ active: !isShowPhone }"
          @click="showQr"
          >微信扫码登录</a
        >
      </section>
      <div class="content">
        <div class="phonebox" v-show="isShowPhone">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <!-- <input type="text" placeholder="滑动滑块" /> -->
            <slide-verify
              :l="42"
              :r="20"
              :w="355"
              :h="137"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="imgsarr"
            ></slide-verify>
          </div>
          <div class="row">
            <input type="text" placeholder="请输入验证码" v-model="codeval" />
            <button class="btncode" @click="getcode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="btncode" v-show="isShowCount">{{ count }}s</button>
          </div>
          <div class="row">
            <button class="btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 显示微信二维码第二步 -->
        <div class="qrbox" v-show="!isShowPhone" id="wechat">微信登录</div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import { validatePhoneNumber } from "@/utils";
import { SendSMSAPI, PhoneReginAPI, BindingAPI } from "@/request/api";
export default {
  data() {
    return {
      isShowPhone: true,
      msg: "向右滑动",
      imgsarr: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-02.150d92a1.png"),
        require("../assets/img/integral-03.9870f3f1.png"),
        require("../assets/img/integral-04.afadcbdf.png"),
      ],
      phoneNumber: "",
      count: 5,
      isShowCount: false,
      codeval: "",
      // isshow:""
    };
  },
  methods: {
    ...mapActions({
      asyncIsShowToast: "showToast/asyncIsShowToast",
      asyncchangeUserInfo: "userInfo/asyncchangeUserInfo",
    }),
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      changeIsLoginStatus: "loginStatus/changeIsLoginStatus",
      // changeIsShowToast:"showToast/changeIsShowToast",
    }),

    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },

    toVerify() {
      //1.判断用户是否输入手机号 不正确时 提示 （正则表达式）
      if (!validatePhoneNumber(this.phoneNumber)) {
        // alert("请输入正确的手机号码");
        this.asyncIsShowToast({
          isshow: true,
          msg: "请输入正确的手机号码",
          type: "danger",
        });
        return;
      }
      //2.判断滑块验证码  不正确时 提示
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        // alert("请滑动验证码！！！");
        this.asyncIsShowToast({
          isshow: true,
          msg: "请滑动验证码",
          type: "danger",
        });
        return;
      }
      // console.log("手机号和滑块验证通过");
      return true;
    },

    //获取验证码
    async getcode() {
      let flag = this.toVerify();
      // console.log("来了来了", flag);
      if (!flag) return;
      //3.发送验证码（发请求） 请求成功后，倒计时。
      //【第二步：调用方法，传递参数】
      let res = await SendSMSAPI({
        phone: this.phoneNumber,
      });
      // console.log("res*", res);
      if (!res) return;
      alert("发送成功");
      if (res.code == 0) {
        this.isShowCount = true;
        let timer = setInterval(() => {
          this.count--;
          if (this.count == 0) {
            clearInterval(timer);
            this.count = 5;
            this.isShowCount = false;
          }
        }, 1000);
      }
    },

    // 登录
    async submitFn() {
      // if (!this.toVerify()) return;
      // if (this.codeval == "") {
      //   alert("短信验证码不能为空");
      //   return;
      // }

      // 根据uuid区分是否是手机绑定微信
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await BindingAPI({
          verifyCode: this.codeval,
          phone: this.phoneNumber,
          uuid,
        });
      } else {
        res = await PhoneReginAPI({
          verifyCode: this.codeval,
          phone: this.phoneNumber,
        });
      }

      // console.log("登录请求:", res);
      if (!res) return;
      //1.提示登录成功
      alert("登录成功");
      //2.本地存储token
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      //3.关闭模态框
      this.changeIsShowLoginModal(false);
      //4.显示购物车按钮
      this.changeIsLoginStatus(true);
      //删除uuid
      localStorage.removeItem("uuid");

      //调用actions内方法请求用户信息
      this.asyncchangeUserInfo();
    },
    showQr() {
      this.isShowPhone = false;
      //获取二维码
      let _this = this;
      new WxLogin({
        id: "wechat",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href:
          "data:text/css;base64,Lm9sZC10ZW1wbGF0ZSAudGl0bGUsLmluZm97DQogICAgZGlzcGxheTogbm9uZTsNCn0=",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    background-color: rgba(0, 0, 0, 0.5);
    width: 100%;
    height: 100%;
  }
  .loginbox {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      right: 55px;
      top: 10px;
      width: 22px;
      height: 22px;
      background: url("../assets/img/close.png");
      cursor: pointer;
    }
    .nav {
      text-align: center;
      padding-top: 30px;
      font-style: 18px;
      a {
        text-decoration: none;
        color: #000;
        &.active {
          color: #0a328e;
        }
      }
    }
    .content {
      width: 355px;
      //   background-color: pink;
      margin: 10px auto 0;
      .phonebox {
        margin-top: 20px;
        .row {
          display: flex;
          margin-bottom: 30px;
          input {
            flex: 1;
            height: 50px;
            text-indent: 1em;
            outline: none;
            border: 1px solid #ccc;
          }
          button {
            height: 50px;
            background-color: #0a328e;
            color: white;
            border: none;
          }
          .btncode {
            margin-left: 10px;
            height: 55px;
            width: 86px;
            cursor: pointer;
          }
          .btnlogin {
            width: 100%;
          }
        }
      }
      .qrbox {
        text-align: center;
        margin-top: 20px;
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>